<template>
  <div class="exhibition-list-container">
    <el-card>
      <div slot="header" class="card-header">
        <span>展览列表</span>
        <el-input
          placeholder="搜索展览名称"
          v-model="searchQuery"
          class="search-input"
          clearable
          @clear="getExhibitionList"
          @keyup.enter.native="searchExhibitions"
        >
          <el-button slot="append" icon="el-icon-search" @click="searchExhibitions"></el-button>
        </el-input>
      </div>
      
      <!-- 展览列表 -->
      <el-row :gutter="20" v-loading="loading">
        <el-col 
          :xs="24" 
          :sm="12" 
          :md="8" 
          :lg="6" 
          v-for="item in exhibitionList" 
          :key="item.id" 
          class="exhibition-item"
        >
          <el-card :body-style="{ padding: '0px' }" shadow="hover" class="exhibition-card">
            <div class="exhibition-img">
              <img :src="item.image && item.image.startsWith('data:image') ? item.image : 'data:image/jpeg;base64,' + item.image" alt="展览图片">
              <div class="exhibition-status" :class="getStatusClass(item.status)">
                {{ getStatusText(item.status) }}
              </div>
            </div>
            <div class="exhibition-info">
              <h3 class="exhibition-title">{{ item.name }}</h3>
              <p class="exhibition-time">{{ formatDateRange(item.startTime, item.endTime) }}</p>
              <p class="exhibition-location">{{ item.location }}</p>
              <div class="exhibition-footer">
                <el-button type="primary" size="small" @click="viewDetail(item.id)">查看详情</el-button>
                <el-button 
                  type="success" 
                  size="small" 
                  @click="makeReservation(item)" 
                  :disabled="item.status !== 'IN_PROGRESS'"
                >预约参观</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 空数据提示 -->
      <el-empty 
        v-if="exhibitionList.length === 0 && !loading" 
        description="暂无展览信息"
      ></el-empty>
      
      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[8, 16, 24, 32]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      >
      </el-pagination>
    </el-card>
    
    <!-- 预约对话框 -->
    <el-dialog 
      title="展览预约" 
      :visible.sync="dialogVisible" 
      width="500px"
      :before-close="handleDialogClose"
    >
      <el-form 
        :model="reservationForm" 
        :rules="reservationRules" 
        ref="reservationFormRef" 
        label-width="100px"
      >
        <el-form-item label="展览名称">
          <el-input v-model="currentExhibition.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="展览地点">
          <el-input v-model="currentExhibition.location" disabled></el-input>
        </el-form-item>
        <el-form-item label="预约日期" prop="reservationDate">
          <el-date-picker
            v-model="reservationForm.reservationDate"
            type="date"
            placeholder="选择预约日期"
            :picker-options="datePickerOptions"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间段" prop="timeSlot">
          <el-select 
            v-model="reservationForm.timeSlot" 
            placeholder="请选择预约时间段" 
            style="width: 100%"
          >
            <el-option
              v-for="item in timeSlots"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约人数" prop="visitorCount">
          <el-input-number 
            v-model="reservationForm.visitorCount" 
            :min="1" 
            :max="10" 
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="submitReservation" :loading="submitLoading">提交预约</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  name: 'ExhibitionList',
  data() {
    return {
      // 展览列表数据
      exhibitionList: [],
      // 默认展览图片
      defaultImage: 'https://via.placeholder.com/300x200?text=文化馆展览',
      // 加载状态
      loading: false,
      // 分页参数
      currentPage: 1,
      pageSize: 8,
      total: 0,
      // 搜索关键词
      searchQuery: '',
      // 预约对话框
      dialogVisible: false,
      // 当前选中的展览
      currentExhibition: {},
      // 预约表单
      reservationForm: {
        reservationDate: '',
        timeSlot: '',
        visitorCount: 1
      },
      // 预约表单验证规则
      reservationRules: {
        reservationDate: [
          { required: true, message: '请选择预约日期', trigger: 'change' }
        ],
        timeSlot: [
          { required: true, message: '请选择预约时间段', trigger: 'change' }
        ],
        visitorCount: [
          { required: true, message: '请输入预约人数', trigger: 'blur' },
          { type: 'number', min: 1, max: 10, message: '预约人数必须在1-10人之间', trigger: 'blur' }
        ]
      },
      // 日期选择器配置
      datePickerOptions: {
        disabledDate(time) {
          // 禁用今天之前的日期
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      // 时间段选项
      timeSlots: [
        { value: '09:00-11:00', label: '上午 09:00-11:00' },
        { value: '13:00-15:00', label: '下午 13:00-15:00' },
        { value: '15:00-17:00', label: '下午 15:00-17:00' }
      ],
      // 提交预约加载状态
      submitLoading: false
    }
  },
  created() {
    // 获取展览列表
    this.getExhibitionList()
  },
  methods: {
    // 获取展览列表
    async getExhibitionList() {
      this.loading = true
      try {
        const { data: res } = await this.$http.get('/exhibition/list', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            keyword: this.searchQuery
          }
        })
        
        if (res.code === 200) {
          this.exhibitionList = res.data.records || []
          this.total = res.data.total || 0
        } else {
          this.$message.error(res.message || '获取展览列表失败')
        }
      } catch (error) {
        console.error('获取展览列表失败', error)
        this.$message.error('获取展览列表失败，请稍后重试')
        // 使用模拟数据
        this.exhibitionList = this.getMockData()
        this.total = this.exhibitionList.length
      } finally {
        this.loading = false
      }
    },
    
    // 搜索展览
    searchExhibitions() {
      this.currentPage = 1
      this.getExhibitionList()
    },
    
    // 处理页码变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.getExhibitionList()
    },
    
    // 处理每页条数变化
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.currentPage = 1
      this.getExhibitionList()
    },
    
    // 查看展览详情
    viewDetail(id) {
      if (!id) {
        this.$message.warning('展览ID不存在')
        return
      }
      this.$router.push(`/exhibition/detail/${id}`)
    },
    
    // 打开预约对话框
    makeReservation(exhibition) {
      if (!exhibition || !exhibition.id) {
        this.$message.warning('展览信息不完整')
        return
      }
      
      this.currentExhibition = exhibition
      this.dialogVisible = true
      
      // 重置表单
      this.reservationForm = {
        reservationDate: '',
        timeSlot: '',
        visitorCount: 1
      }
      
      // 如果表单引用存在，重置验证
      this.$nextTick(() => {
        if (this.$refs.reservationFormRef) {
          this.$refs.reservationFormRef.resetFields()
        }
      })
    },
    
    // 关闭对话框
    handleDialogClose() {
      this.$refs.reservationFormRef.resetFields()
      this.dialogVisible = false
    },
    
    // 提交预约
    submitReservation() {
      this.$refs.reservationFormRef.validate(async valid => {
        if (!valid) return
        
        this.submitLoading = true
        try {
          // 构建预约数据
          const reservationData = {
            userId: this.$store.state.userInfo.id,
            exhibitionId: this.currentExhibition.id,
            reservationDate: moment(this.reservationForm.reservationDate).format('YYYY-MM-DD'),
            timeSlot: this.reservationForm.timeSlot,
            visitorCount: this.reservationForm.visitorCount
          }
          
          // 发送预约请求
          const { data: res } = await this.$http.post('/exhibition-reservation', reservationData)
          
          if (res.code === 200) {
            this.$message.success('预约成功，请在"我的预约"中查看')
            this.dialogVisible = false
          } else {
            this.$message.error(res.message || '预约失败')
          }
        } catch (error) {
          console.error('预约失败', error)
          this.$message.error('预约失败，请稍后重试')
        } finally {
          this.submitLoading = false
        }
      })
    },
    
    // 格式化日期范围
    formatDateRange(startTime, endTime) {
      if (!startTime || !endTime) return ''
      return `${moment(startTime).format('YYYY-MM-DD')} - ${moment(endTime).format('YYYY-MM-DD')}`
    },
    
    // 获取展览状态样式类
    getStatusClass(status) {
      switch (status) {
        case 'UPCOMING':
          return 'status-upcoming'
        case 'ONGOING':
          return 'status-ongoing'
        case 'FINISHED':
          return 'status-finished'
        default:
          return ''
      }
    },
    
    // 获取展览状态文本
    getStatusText(status) {
      switch (status) {
        case 'UPCOMING':
          return '即将开始'
        case 'ONGOING':
          return '进行中'
        case 'FINISHED':
          return '已结束'
        default:
          return ''
      }
    },
    
    // 模拟数据
    getMockData() {
      const mockData = []
      for (let i = 1; i <= 10; i++) {
        mockData.push({
          id: i,
          name: `展览${i}`,
          image: 'https://via.placeholder.com/300x200?text=展览图片',
          status: i % 3 === 0 ? 'ONGOING' : (i % 3 === 1 ? 'UPCOMING' : 'FINISHED'),
          startTime: moment().add(i, 'days').format('YYYY-MM-DD'),
          endTime: moment().add(i + 30, 'days').format('YYYY-MM-DD'),
          location: `文化馆${i}号展厅`
        })
      }
      return mockData
    }
  }
}
</script>

<style scoped>
.exhibition-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  max-width: 300px;
}

.exhibition-item {
  margin-bottom: 20px;
}

.exhibition-card {
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.exhibition-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.exhibition-img {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.exhibition-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.exhibition-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  color: #fff;
  font-size: 12px;
  font-weight: bold;
}

.status-upcoming {
  background-color: #409EFF;
}

.status-ongoing {
  background-color: #67C23A;
}

.status-finished {
  background-color: #909399;
}

.exhibition-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.exhibition-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.exhibition-time, .exhibition-location {
  margin: 5px 0;
  font-size: 14px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.exhibition-footer {
  margin-top: auto;
  display: flex;
  justify-content: space-between;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

/* 预约对话框样式 */
.dialog-footer {
  text-align: right;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .search-input {
    max-width: 100%;
    margin-top: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .exhibition-footer {
    flex-direction: column;
  }
  
  .exhibition-footer .el-button {
    margin-left: 0;
    margin-top: 10px;
    width: 100%;
  }
}
</style>